<template>
  <div id="chart"></div>
</template>

<script>
import {Graph} from '@antv/x6'

const data = {
  nodes: [
    {
      id: 'a1',
      x: 40, y: 40,
      width: 60, height: 40,
      zIndex: 10,
      label: 'chidl1',
      attrs: {
        body: {
          fill: 'orange'
        }
      }
    },
    {
      x: 540, y: 40,
      id: 'b1',
      width: 60, height: 40,
      zIndex: 10,
      label: 'chidl2',
      attrs: {
        body: {
          fill: 'pink'
        }
      }
    },
    {
      x: 240, y: 300,
      width: 360, height: 240,
      zIndex: 1,
      label: 'parent',
      attrs: {
        body: {
          stroke: 'orange'
        }
      },
      data: {
        parent: true,
      },
    }
  ],
  edges: [
    {
      source: 'a1',
      target: 'b1'
    }
  ]
}

export default {
  name: 'Group',
  methods: {
    createGraph() {
      const graph = new Graph({
        container: document.getElementById('chart'),
        width: window.innerWidth,
        height: window.innerHeight,
        grid: {
          visible: true
        },
        background: {
          color: '#fffbe6'
        },
        embedding: {
          enabled: true,
          findParent({ node }) {
            const bbox = node.getBBox()
            return this.getNodes().filter((node) => {
              // 只有 data.parent 为 true 的节点才是父节点
              const data = node.getData()
              if (data && data.parent) {
                const targetBBox = node.getBBox()
                return bbox.isIntersectWithRect(targetBBox)
              }
              return false
            })
          }
        },
        highlighting: { // 在移动到父节点的里面的时候   设置父节点的样式
          embedding: {
            name: 'stroke',
            args: {
              padding: -1,
              attrs: {
                stroke: 'red',
              },
            },
          },
        },
        translating: {  // 设置子元素的 位置限制  不能移动出去
          restrict(view) {
            const cell = view.cell
            if (cell.isNode()) {
              const parent = cell.getParent()
              if (parent) {
                return parent.getBBox()
              }
            }
            return null
          },
        },
      })
      graph.fromJSON(data)
    }
  },
  mounted() {
    this.createGraph()
  }
}
</script>

<style>

</style>